package development.app.football;

import java.util.Vector;

import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.SMSHandler;
import state.SendSMSListener;
import state.Sprite;
import state.component.Checkbox;
import state.component.Event;
import state.component.EventListener;
import state.component.GameScrollBar;
import state.component.GridMenu;
import state.component.MultiTab;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.NumberUtil;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.Utils;
import development.bean.Category;
import development.bean.Content;
import development.bean.SMSServiceCommand;
import development.bean.Subscription;
import development.group.FrmGroupBongDaXoSo;
import development.group.FrmGroupNapXuAndExchangeGold;

public class FrmBongDa extends GameForm implements EventListener, SendSMSListener {
  public static final int FOOTBALL_CATEGORY_REQUEST = 1200;
  public static final int FOOTBALL_CATEGORY_RESPONSE = 1201;

  public static final int FOOTBALL_CONTENT_REQUEST = 1202;
  public static final int FOOTBALL_CONTENT_RESPONSE = 1203;

  public static final int FOOTBALL_PROGRAM_BETTING_ONLINE_REQUEST = 1204;
  public static final int FOOTBALL_PROGRAM_BETTING_ONLINE_RESPONSE = 1205;

  // public static final int FOOTBALL_PROGRAM_PHASE_BETTING_ONLINE_REQUEST = 1206;
  public static final int FOOTBALL_PROGRAM_PHASE_BETTING_ONLINE_RESPONSE = 1207;

  public static final int FOOTBALL_BETTING_OBJECT_ONLINE_REQUEST = 1208;
  public static final int FOOTBALL_BETTING_OBJECT_ONLINE_RESPONSE = 1209;

  // public static final int FOOTBALL_BETTING_SUBMIT_ONLINE_REQUEST = 1210;
  public static final int FOOTBALL_BETTING_SUBMIT_ONLINE_RESPONSE = 1211;

  private final String FIRST_CATEGORY_CODE = "FOOTBALL";

  private ImageText text8;
  private ImageText text11;
  private Content content;
  private int categoryIndex;
  private String formType;
  private Hashtable logAction = null;
  private int currentAction;
  private int dy;

  private Vector categories;
  private Vector categoriesPath;

  private final int DEFAULT_TEXT_X = 5;
  private int CATEGORY_IMAGE_HEIGHT;
  private GameScrollBar scrollBar;
  private Clip textView;
  private Hashtable parameters;

  private final String WAITING_MESSAGE = "Xin chờ trong giây lát...";
  private int packageNumber;
  private int totalPackage;
  private int percent;
  
  private GridMenu gridMenu;
  
  private String SMS_SERVICE_COMMAND;

  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmBongDa();
    }
    return singleton;
  }

  public void init(Hashtable parameters1) {
    this.parameters = parameters1;
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);

    categoriesPath = new Vector();
    categories = new Vector();

    content = new Content();
    logAction = new Hashtable();
    currentAction = 1;
    formType = "category";
    CATEGORY_IMAGE_HEIGHT = 50;
    dy = DrawUtils.getTopBarHeight();
    
    gridMenu = new GridMenu(_manager, null, null, 1, 0, DrawUtils.getTopBarHeight(), Global.getDefaultAvatar().getHeight() + 5, Global.getDefaultAvatar().getWidth() + 5, this);
    gridMenu.setVisible(false);

    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10); // Là khung nhìn để vẽ đoạn text ra
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);

    if (parameters1 != null) {
      String strCategory = (String) parameters1.get("category");
      if (strCategory != null) {
        request(FOOTBALL_PROGRAM_BETTING_ONLINE_REQUEST, strCategory);
      } else {
        request(FOOTBALL_CATEGORY_REQUEST, new StringArray(new String[]{FIRST_CATEGORY_CODE}, 1));
      }
    } else {
      request(FOOTBALL_CATEGORY_REQUEST, new StringArray(new String[]{FIRST_CATEGORY_CODE}, 1));
    }
    //manager.enableTouchPad();
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (categories.isEmpty()) {
      text8.drawString2(g, WAITING_MESSAGE, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_HCENTER_ANCHOR);
    }
    if (formType.equals("category") && categories.size() != 0) {
      drawCategory(g);
    }
    if (formType.equals("content") && content != null && content.detail.size() > 0) {
      drawContent(g);
    }
    drawMenu(g);
    text8.drawString2(g, GameStringUtils.join(categoriesPath, "-"), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 5, GameConstants.TOP_HCENTER_ANCHOR);
  }

  private void drawMenu(Graphics g) {
    if (formType.equals("bettingObject_FOOTBALL_KQ") || formType.equals("bettingObject_FOOTBALL_TAI_XIU") || formType.equals("bettingObject_FOOTBALL_TS")) {
      DrawUtils.getBottomBar(_manager).setCenterLabel("Đồng ý");
    }
    if (formType.equals("content") || formType.equals("bettingObject_FOOTBALL_KQ") || formType.equals("bettingObject_FOOTBALL_TAI_XIU") || formType.equals("bettingObject_FOOTBALL_TS")) {
      DrawUtils.getBottomBar(_manager).setLeftLabel("Menu chính");
    }
    if (formType.equals("category") || formType.equals("content") || formType.equals("FOOTBALL_KQ") || formType.equals("FOOTBALL_TAI_XIU") || formType.equals("FOOTBALL_TS")
        || formType.equals("BETTING_ONLINE")) {
      DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
    }
  }

  private void drawContent(Graphics g) {
    int textY = dy;
    if(content.contentType.equals("FOOTBALL")){
      for (int i = 0; i < content.detail.size(); i++) {
        String detail = (String) content.detail.elementAt(i);
        if(detail.startsWith(" ")){
          g.setColor(0xA9A9A9);
          g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
          g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
          text11.drawString3(g, detail, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_HCENTER_ANCHOR, scrollBar);
          textY = textY + 20;
        }
        else {
          text8.drawString3(g, detail, GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          textY = textY + 20;
        }
        g.setColor(0xC0C0C0);
        g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      }
    }
    else if (content.contentType.equals("LIVE_SCORE")) {
      for (int i = 0; i < content.detail.size(); i++) {
        String detail = (String) content.detail.elementAt(i);
        if (detail.endsWith("@@@LEAGUE")) {
          detail = GameStringUtils.replaceAll(detail, "@@@LEAGUE", "");
          g.setColor(0xA9A9A9);
          g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
          g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
          text11.drawString3(g, detail, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_HCENTER_ANCHOR, scrollBar);
          textY = textY + 20;
        } else {
          text8.drawString3(g, detail, GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          textY = textY + 20;
        }
        g.setColor(0xC0C0C0);
        g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      }
    } else if (content.contentType.equals("TOP_GHI_BAN")) {
      g.setColor(0xA9A9A9);
      g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
      g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
      text11.drawString3(g, "Tên cầu thủ", GameColor.WHITE_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      text11.drawString3(g, "Số BT", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 50, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      for (int i = 0; i < content.detail.size(); i++) {
        StringArray arrContent = (StringArray) content.detail.elementAt(i);
        text8.drawString3(g, arrContent.array[0], GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        text8.drawString3(g, arrContent.array[1], GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 20, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        textY = textY + 20;
        g.setColor(0xC0C0C0);
        g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      }
    } else if (content.contentType.equals("LICH_THI_DAU")) {
      g.setColor(0xA9A9A9);
      g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
      g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
      text11.drawString3(g, "Ngày/giờ", GameColor.WHITE_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      text11.drawString3(g, "Trận đấu", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2 - 20, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      for (int i = 0; i < content.detail.size(); i++) {
        StringArray arrContent = (StringArray) content.detail.elementAt(i);
        text8.drawString3(g, arrContent.array[0], GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        text8.drawString3(g, arrContent.array[1], GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH / 2 - 40, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        textY = textY + 20;
        g.setColor(0xC0C0C0);
        g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      }
    } else if (content.contentType.equals("BANG_XEP_HANG")) {
      g.setColor(0xA9A9A9);
      g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
      g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
      text11.drawString3(g, "Đội", GameColor.WHITE_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      text11.drawString3(g, "Số trân", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2 - 20, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      text11.drawString3(g, "Điểm", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 40, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      for (int i = 0; i < content.detail.size(); i++) {
        StringArray arrContent = (StringArray) content.detail.elementAt(i);
        text8.drawString3(g, arrContent.array[0], GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        text8.drawString3(g, arrContent.array[1], GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        text8.drawString3(g, arrContent.array[2], GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 20, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
        textY = textY + 20;
        g.setColor(0xC0C0C0);
        g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      }
    } else if (content.contentType.equals("TY_LE")) {
      for (int i = 0; i < content.detail.size(); i++) {
        StringArray arrContent = (StringArray) content.detail.elementAt(i);
        if (arrContent.len() == 1) {
          g.setColor(0xA9A9A9);
          g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
          g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
          text11.drawString3(g, arrContent.array[0], GameColor.WHITE_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          textY = textY + 20;
          g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
        } else {
          for (int j = 0; j < arrContent.len(); j++) {
            if (j == arrContent.len() - 1) {
              text8.drawString3(g, arrContent.array[j], GameColor.WHITE_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, arrContent.array[j], GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            }
            textY = textY + 20;
          }
          g.setColor(0xC0C0C0);
          g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
        }
      }
    } else {
      for (int i = 0; i < content.detail.size(); i++) {
        String detail = (String) content.detail.elementAt(i);
        textY = text8.drawParagraph2(g, detail, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 10, DEFAULT_TEXT_X, textY, scrollBar);
      }
    }

    text8.drawString3(g, ".", GameColor.WHITE_CODE, 0, textY + 50, Constants.TOP_LEFT_ANCHOR, scrollBar);
    scrollBar.draw(g);
  }

  private void drawCategory(Graphics g) {
//    int textY = dy;
//    int index = 0;
//    if (categoryIndex == 0) {
//      dy = DrawUtils.getTopBarHeight();
//    }
//    for (int i = 0; i < categories.size(); i++) {
//      Category category = (Category) categories.elementAt(i);
//      g.drawImage(category.image, 0, textY, GameConstants.TOP_LEFT_ANCHOR);
//      if (!category.hasChild) {
//        text8.drawString(g, category.name, Color.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//      } else {
//        text8.drawString(g, category.name, Color.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//      }
//      if (categoryIndex == index) {
//        g.setColor(0x53A4CF);
//        g.fillRect(0, textY - 7, GameConstants.SCREEN_WIDTH, category.image.getHeight() + 25);
//        g.drawImage(category.image, 0, textY, GameConstants.TOP_LEFT_ANCHOR);
//        if (!category.hasChild) {
//          text8.drawString(g, category.name, Color.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//        } else {
//          text8.drawString(g, category.name, Color.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//        }
//      }
//      if (category.fee > 0) {
//        if (!category.hasChild) {
//          text8.drawString(g, category.fee + "$", Color.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY + category.image.getHeight() / 50, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
//        } else {
//          text8.drawString(g, category.fee + "$", Color.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY + category.image.getHeight() / 3, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
//        }
//      }
//      if (!category.hasChild) {
//        text8.drawString(g, "Chi tiết >>", Color.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY + category.image.getHeight(), GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
//      }
//      g.setColor(0xC0C0C0);
//      g.drawLine(0, textY - 7, GameConstants.SCREEN_WIDTH, textY - 7);
//      textY = textY + category.image.getHeight() + 25;
//      index++;
//    }
//    g.drawLine(0, textY - 7, GameConstants.SCREEN_WIDTH, textY - 7);
//    text8.drawString(g, "", Color.WHITE_CODE, 0, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//    scrollBar.draw(g);
//
//    if (percent < 100) {
//      DrawUtils.getBottomBar(manager).setCenterLabel(percent + "%");
//    } else {
//      DrawUtils.getBottomBar(manager).setCenterLabel("");
//    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    dy = DrawUtils.getTopBarHeight();
    int header = dataPackage.getHeader();
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    formType = mapDataPackage.popString("type");
    if (formType.equals("-1")) {
      Global.alert.showAlert2(this, GameAlert.OK_TYPE, "Chưa có dữ liệu cho mục này", -1);
      return;
    }
    GameGlobal.systemCanvas.hideAlert();
    Category category = null;
    ByteArray btImage = null;
    switch (header) {
    case FOOTBALL_CATEGORY_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      category.hasChild = NumberUtil.parseInt(mapDataPackage.getString("child")) > 0;
      category.fee = mapDataPackage.getInt("fee");
      btImage = mapDataPackage.getByteArray("avatarImage");
      category.image = GameImage.createImage(btImage, 0, btImage.len());
      CATEGORY_IMAGE_HEIGHT = category.image.getHeight();
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      categories.addElement(category);
      gridMenu.setHozDistance(category.image.getHeight() + 5);
      gridMenu.setDisplayTitle(false);
      gridMenu.setVisible(true);
      Sprite sprite = new Sprite(null, null, 0, 0, Constants.TOP_LEFT_ANCHOR);
      sprite.setSize(GameConstants.SCREEN_WIDTH - 10, Global.getDefaultAvatar().getHeight() + 5);
      sprite.setId((byte) (categories.size() - 1));
      gridMenu.addSpriteItem(sprite, category.id);
      sprite.setDrawListener(new DrawListener() {
        public void paint(Sprite source, Graphics g) {
          int index = source.getId();
          Category category1 = (Category) categories.elementAt(index);
          g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
          if (!category1.hasChild) {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          } else {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          }
          if (gridMenu.getCurrentSelectedIndex() == index) {
            g.setColor(0x53A4CF);
            g.fillRect(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, category1.image.getHeight() + 7);
            g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
            if (!category1.hasChild) {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            }
          }
          if (category1.fee > 0) {
            if (!category1.hasChild) {
              text8.drawString3(g, category1.fee + "$", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.fee + "$", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            }
          }
          if (!category1.hasChild) {
            text8.drawString3(g, "Chi tiết >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + 30, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
          }
          g.setColor(0xC0C0C0);
          g.drawLine(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, source.getRealY() - 7);
          if(index == gridMenu.getNumberOfItem() - 1){
            g.setColor(0xC0C0C0);
            g.drawLine(0, source.getRealY() + category1.image.getHeight() + 2, GameConstants.SCREEN_WIDTH, source.getRealY() + category1.image.getHeight() + 2);
          }
        }
      });
      _manager.disableTouchPad();
      break;
    case FOOTBALL_CONTENT_RESPONSE:
      String error = mapDataPackage.popString("error");
      if (error != null && !error.equals("")) {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, error);
        return;
      }
      content.contentType = mapDataPackage.popString("contentType");
      Vector names = mapDataPackage.getNames();
      String keyContent = null;
      if (!names.isEmpty()) {
        keyContent = mapDataPackage.getNames().elementAt(0).toString();
      }
      if (keyContent == null || keyContent.equals("")) {
        return;
      }
      String strResponse = mapDataPackage.getString(keyContent);
      if (content.contentType.equals("TY_LE") || content.contentType.equals("BANG_XEP_HANG") || content.contentType.equals("LICH_THI_DAU") || content.contentType.equals("TOP_GHI_BAN")) {
        StringArray arrContent = GameStringUtils.split(strResponse, "@@@");
        content.detail.addElement(arrContent);
      } else if (content.contentType.equals("LIVE_SCORE")) {
        content.detail.addElement(strResponse);
      } else {
        content.detail.addElement(strResponse);
      }
      _manager.enableTouchPad();
      break;
    case FOOTBALL_PROGRAM_BETTING_ONLINE_RESPONSE:
      category = new Category();
      category.id = mapDataPackage.getString("programId");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      category.hasChild = NumberUtil.parseInt(mapDataPackage.getString("child")) > 0;
      btImage = mapDataPackage.getByteArray("avatarImage");
      category.image = GameImage.createImage(btImage, 0, btImage.len());
      if (!categories.contains(category)) {
        categories.addElement(category);
      }
      gridMenu.setHozDistance(category.image.getHeight() + 5);
      gridMenu.setDisplayTitle(false);
      gridMenu.setVisible(true);
      sprite = new Sprite(null, null, 0, 0, Constants.TOP_LEFT_ANCHOR);
      sprite.setSize(GameConstants.SCREEN_WIDTH - 10, Global.getDefaultAvatar().getHeight() + 5);
      sprite.setId((byte) (categories.size() - 1));
      gridMenu.addSpriteItem(sprite, category.id);
      sprite.setDrawListener(new DrawListener() {
        public void paint(Sprite source, Graphics g) {
          int index = source.getId();
          Category category1 = (Category) categories.elementAt(index);
          g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
          if (!category1.hasChild) {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          } else {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          }
          if (gridMenu.getCurrentSelectedIndex() == index) {
            g.setColor(0x53A4CF);
            g.fillRect(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, category1.image.getHeight() + 7);
            g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
            if (!category1.hasChild) {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            }
          }
          if (category1.fee > 0) {
            if (!category1.hasChild) {
              text8.drawString3(g, category1.fee + "$", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.fee + "$", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
            }
          }
          if (!category1.hasChild) {
            text8.drawString3(g, "Chi tiết >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + 30, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
          }
          g.setColor(0xC0C0C0);
          g.drawLine(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, source.getRealY() - 7);
          if(index == gridMenu.getNumberOfItem() - 1){
            g.setColor(0xC0C0C0);
            g.drawLine(0, source.getRealY() + category1.image.getHeight() + 2, GameConstants.SCREEN_WIDTH, source.getRealY() + category1.image.getHeight() + 2);
          }
        }
      });
      _manager.disableTouchPad();
      break;
    case FOOTBALL_PROGRAM_PHASE_BETTING_ONLINE_RESPONSE:
      category = new Category();
      String key = (String) mapDataPackage.getNames().elementAt(0);
      String value = mapDataPackage.getString(key);
      StringArray arr = GameStringUtils.split(value, "@@@");
      category.id = key;
      category.code = key;
      category.name = arr.get(0) + " " + arr.get(1) + " " + arr.get(2);
      StringArray arrDesc = GameStringUtils.split(arr.get(0), "\n");
      for (int i = 0; i < arrDesc.len(); i++) {
        category.exParam.addElement(arrDesc.get(i));
      }
      category.exParam.addElement("Thời gian dự đoán:");
      category.exParam.addElement(arr.get(1) + " đến " + arr.get(2));
      category.hasChild = false;
      category.image = Global.getDefaultAvatar();
      if (!categories.contains(category)) {
        categories.addElement(category);
      }
      _manager.enableTouchPad();
      break;
    case FOOTBALL_BETTING_OBJECT_ONLINE_RESPONSE:
      Vector keys = mapDataPackage.getNames();
      for (int i = 0; i < keys.size(); i++) {
        key = (String) keys.elementAt(i);
        category = new Category();
        category.id = key;
        StringArray params = GameStringUtils.split(mapDataPackage.getString(key), "@@@");
        category.code = params.get(0);
        category.cb = new Checkbox(_manager, this, Constants.CHECK_BOX_STYLE_APP, 0, 0);
        category.cb.setLabel(params.get(1));
      }
      _manager.enableTouchPad();
      break;
    case FOOTBALL_BETTING_SUBMIT_ONLINE_RESPONSE:
      int status = mapDataPackage.getInt("status");
      if (status == 1) {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn đã cược thành công");
      } else {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn đã cược không thành công");
      }
      _manager.enableTouchPad();
      break;
    }
  }
  
  public void onActionPerform(Event event) {
    if (MultiTab.OPEN_TAB_EVENT.equals(event.getAction())) {
      DrawUtils.setBottomBar(_manager, "Menu chính", "Chọn", "Trở về");
      return;
    }
    if (event.getSource() == gridMenu) {
      process(gridMenu.getCurrentSelectedIndex());
    }
  }
  private void process(int index) {
    if (!isLoadingCompleted()) {
      return;
    }
    if (formType.equals("FOOTBALL_KQ") || formType.equals("FOOTBALL_TS") || formType.equals("FOOTBALL_TAI_XIU")) {
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
      currentAction++;
      Category category = (Category) categories.elementAt(index);
      request(FOOTBALL_BETTING_OBJECT_ONLINE_REQUEST, new StringArray(new String[] { category.id }, 1));
      clearCategory();
      gridMenu.setVisible(false);
      if (!categoriesPath.contains(category.name)) {
        categoriesPath.addElement(category.name);
      }
      return;
    }
    if (formType.equals("category")) {
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
      Category category = (Category) categories.elementAt(index);
      if (!validateUserMoney(category.fee)) {
        return;
      }
      currentAction++;
      if (category.code.equals("BETTING_ONLINE")) {
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        request(FOOTBALL_PROGRAM_BETTING_ONLINE_REQUEST, new StringArray(new String[] { category.code },1));
        clearCategory();
        gridMenu.setVisible(false);
        if (!categoriesPath.contains(category.name)) {
          categoriesPath.addElement(category.name);
        }
        return;
      }
      if (category.code.equals("FOOTBALL_KQ") || category.code.equals("FOOTBALL_TS") || category.code.equals("FOOTBALL_TAI_XIU")) {
        FrmBongDaBetting.instance().detroyAll();
        Hashtable parameters1 = new Hashtable();
        parameters1.put("RequestType", "FOOTBALL");
        parameters1.put("program", category.code);
        FrmBongDaBetting.backTab = this;
        FrmGroupBongDaXoSo frmGroupBongDaXoSo = (FrmGroupBongDaXoSo) FrmGroupBongDaXoSo.instance();
        frmGroupBongDaXoSo.getMultiTab().setTab(1, FrmBongDaBetting.instance(), parameters1);
        return;
      }
      if (category.hasChild) {
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        request(FOOTBALL_CATEGORY_REQUEST, new StringArray(new String[] { category.code },1));
        clearCategory();
        if (!categoriesPath.contains(category.name)) {
          categoriesPath.addElement(category.name);
        }
        return;
      } else {
        if (formType.equals("content") || formType.equals("LIVE_SCORE") || formType.equals("TOP_GHI_BAN") || formType.equals("LICH_THI_DAU") || formType.equals("BANG_XEP_HANG")
            || formType.equals("TY_LE")) {
          return;
        }
        SMS_SERVICE_COMMAND = category.code;
        Subscription sub = Utils.getSubcription(SMS_SERVICE_COMMAND, SMS_SERVICE_COMMAND);
        if (sub == null || sub.status == Subscription.EXPIRED) {
          SMSServiceCommand sms = Utils.getSMSServiceCommand(SMS_SERVICE_COMMAND, SMS_SERVICE_COMMAND);
          if (sms != null) {
            Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Bạn muốn đăng ký dịch vụ", "nhận " + SMS_SERVICE_COMMAND, "hàng tuần không?" ), 10000);
            return;
          }
        }
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
        request(FOOTBALL_CONTENT_REQUEST, new StringArray(new String[] { category.id, String.valueOf(category.fee) }, 2));
        if (!categoriesPath.contains(category.name)) {
          categoriesPath.addElement(category.name);
        }
        gridMenu.setVisible(false);
        return;
      }
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.DOWN:
      if (!categories.isEmpty()) {
        if (formType.equals("category") || formType.equals("FOOTBALL_KQ") || formType.equals("FOOTBALL_TS") || formType.equals("FOOTBALL_TAI_XIU")) {
          if (categoryIndex < categories.size() - 1) {
            categoryIndex++;
          }
        }
      }
      if (formType.equals("category")) {
        if (categories.size() * (CATEGORY_IMAGE_HEIGHT + 25) < GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight()) {
          return;
        }
        if (scrollBar.canScrollUp()) {
          dy = dy - (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      if (formType.equals("content") || formType.equals("LIVE_SCORE") || formType.equals("TOP_GHI_BAN") || formType.equals("LICH_THI_DAU") || formType.equals("BANG_XEP_HANG")
          || formType.equals("TY_LE")) {
        if (scrollBar.canScrollUp()) {
          dy -= 5;
        } else {
          // dy = DrawUtils.getTopBarHeight();
        }
      }
      break;
    case Key.UP:
      if (!categories.isEmpty()) {
        if (formType.equals("category") || formType.equals("FOOTBALL_KQ") || formType.equals("FOOTBALL_TS") || formType.equals("FOOTBALL_TAI_XIU")) {
          if (categoryIndex > 0) {
            categoryIndex--;
          }
        }
      }
      if (formType.equals("content") || formType.equals("LIVE_SCORE") || formType.equals("TOP_GHI_BAN") || formType.equals("LICH_THI_DAU") || formType.equals("BANG_XEP_HANG")
          || formType.equals("TY_LE")) {
        if (scrollBar.canScrollDown()) {
          dy += 5;
        } else {
          dy = DrawUtils.getTopBarHeight();
        }
      }
      if (formType.equals("category")) {
        if (scrollBar.canScrollDown()) {
          dy = dy + (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      break;
    case Key.FIRE:
      process(gridMenu.getCurrentSelectedIndex());
      break;
    case Key.SOFT_LEFT:
      if (!isLoadingCompleted()) {
        return;
      }
      parentGroup.goBack();
      break;
    case Key.SOFT_RIGHT:
      if (!isLoadingCompleted()) {
        return;
      }
      if (content != null && content.detail != null) {
        content.detail.removeAllElements();
      }
      if(!formType.equals("category")){
        _manager.disableTouchPad();
      }
      if (currentAction > 1) {
        clearCategory();
        back();
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
      } else {
        if (parameters != null) {
          String strCategory = (String) parameters.get("category");
          if (strCategory != null) {
            clearCategory();
            parameters = null;
            request(FOOTBALL_CATEGORY_REQUEST, new StringArray(new String[] { FIRST_CATEGORY_CODE },1));
          } else {
            parentGroup.goBack();
          }
        } else {
          parentGroup.goBack();
        }
      }
      break;
    }
  }

  public void keyRepeated(int keyCode) {
    switch (keyCode) {
    case Key.DOWN:
      if (formType.equals("content")) {
        if (scrollBar.canScrollUp()) {
          dy -= 5;
        }
      }
      break;
    case Key.UP:
      if (formType.equals("content")) {
        if (scrollBar.canScrollDown()) {
          dy += 5;
        } else {
          dy = DrawUtils.getTopBarHeight();
        }
      }
      break;
    }
  }

  private boolean validateUserMoney(int fee) {
    if (Global.currentUser.getMoney() < fee) {
      Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Bạn không đủ $ để sử dụng", "dịch vụ này", "Bạn có muốn nạp $ không?" ), 100);
    }
    return true;
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 100 && eventType == GameAlert.YES_BUTTON) {
      FrmGroupNapXuAndExchangeGold.backForm = FrmGroupBongDaXoSo.instance();
      Global.nextState(FrmGroupNapXuAndExchangeGold.instance(), parameters);
    }

    if (alertId == -1 && eventType == GameAlert.OK_TYPE) {
      if (formType.equals("category") || formType.equals("content"))
        if (currentAction > 1) {
          clearCategory();
          back();
        }
    }
    if (alertId == 10000 && eventType == GameAlert.YES_BUTTON) {
      SMSServiceCommand sms = Utils.getSMSServiceCommand(SMS_SERVICE_COMMAND, SMS_SERVICE_COMMAND);
      if (sms != null) {
        SMSHandler.getInstance(this).sendMsg(sms.serviceNumber, sms.command);
      }
    }
  }

  private boolean isLoadingCompleted() {
    return packageNumber == totalPackage;
  }

  private void request(int header, StringArray parameters1) {
    DataPackage dataPackage = DataPackage.createDataPackage1(header);
    for (int i = 0; i < parameters1.len(); i++) {
      dataPackage.putString(parameters1.array[i]);
    }
    Global.appClient.write(dataPackage);
    logAction.put(String.valueOf(currentAction), buildLogAction(header, parameters1));
  }

  private void request(int header, String param) {
    request(header, new StringArray(new String[] { param }, 1));
  }

  private String buildLogAction(int requestType, StringArray parameters1) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(requestType));
    sb.append(",");
    for (int i = 0; i < parameters1.len(); i++) {
      sb.append(parameters1.array[i]);
      sb.append(",");
    }
    if (sb.toString().endsWith(",")) {
      sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
  }

  private void back() {
    currentAction--;
    String values = (String) logAction.get(String.valueOf(currentAction));
    StringArray requestParams = GameStringUtils.split(values, ",");
    int request = NumberUtil.parseInt(requestParams.get(0));
    if (!categoriesPath.isEmpty()) {
      categoriesPath.removeElementAt(categoriesPath.size() - 1);
    }
    request(request, new StringArray(new String[] { requestParams.get(1) },1));
    Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
  }

  private void clearCategory() {
    gridMenu.clearData();
    categories.removeAllElements();
    categoryIndex = 0;
  }

  public void destroy() {
    categoryIndex = 0;
    logAction = null;
    formType = null;
    text8 = null;
    categories = null;
    content = null;
    categoriesPath = null;
    textView = null;
    scrollBar = null;
    parameters = null;
    gridMenu = null;
  }

  public void onSendSMSFail() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Đăng ký thất bại");
  }

  public void onSendSMSSuccess() {
    Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create2( "Đăng ký thành công", "Xin mời bạn quay lại", "trong ít phút" ));
  }
}
